package com.hrt.serial.modbus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.btcode.common.BitType;
import com.btcode.common.ByteUnit;
import com.hrt.datasender.datacollect.drive.DriveConfigModel;

/**
 * modbus数据解析类
 * 
 * @author gislin
 */
public class ModbusDataDecodeTTMB extends ModbusDataDecode {
    private final int dataLengthBytePos = 3;
    private final int msgPrefixLength = 4;  

    /**
     * 
     * @param data
     * @param byteLength
     * @return
     */
    public synchronized List<ModbusDataModel> dataModelDecode(byte[] data, int byteLength, DriveConfigModel deviceConfigs) {
        HashMap<String, String> configsMap = deviceConfigs.getConfig();
        BitType bitType = getBitType(configsMap.get("dataBit"));
        List<ModbusDataModel> models = new ArrayList<>();

        String mn = ByteUnit.ConvertByteToInt8(data[0]) + "";
        /**
         * 整个报文中，数据部分的字节长度 BitType.bit16：两个字节代表一个数据 BitType.bit32：四个字节代表一个数据
         * 所以数据字节长度和真正的业务数据长度不一样 数据字节长度和业务数据有倍数关系
         */
        int dataLength = ByteUnit.ConvertByteToInt8(data[dataLengthBytePos]) / bitType.byteLength;

        double[] resultData = new double[dataLength];

        for (int i = 0; i < dataLength; i++) {
            byte[] dataItem = new byte[bitType.byteLength];
            System.arraycopy(data, msgPrefixLength + i * bitType.byteLength, dataItem, 0, bitType.byteLength);

            double value = ByteUnit.ConvertByteToDoubleX(dataItem, bitType);
            resultData[i] = value;
        }

        ModbusDataModel model = new ModbusDataModel();
        model.setData(resultData);
        model.setDataLength(dataLength);
        model.setId(mn);
        model.setSourceData(data);

        models.add(model);

        return models;

    }

    @Override
    public ModbusDataFrameDecoderBase getDataFrameDecoder(byte[] finalByteData) {
        ModbusDataFrameDecoderBase modbusMsgModel = new ModbusDataFrameDecoderTTMB(finalByteData);
        return modbusMsgModel;
    }

}
